package com.qdxwx.manage.controller.teacher;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.ImageUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.manager.ManagerService;
import com.qdxwx.data.service.subject.SubjectService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.subject.Subject;
import com.qdxwx.models.teacher.Teacher;
import com.qdxwx.models.user.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 讲师Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/teacher")
public class TeacherEditController extends BaseController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private UserService userService;
    @Autowired
    private SubjectService subjectService;
    /**
     * 新增讲师
     */
    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        Teacher teacher = new Teacher();
        teacher.setId(0);
        teacher.setSex(0);
        mmap.put("teacher", teacher);
        mmap.put("subjects", subjectService.getList());
        return "teacher/teacher-edit";
    }
    /**
     * 修改讲师
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") int id, ModelMap mmap) {
        if (id < 1) return error404;
        Teacher teacher = teacherService.get(id);
        if (teacher == null) return error500;
        mmap.put("teacher", teacher);
        mmap.put("subjects",subjectService.getList());
        return "teacher/teacher-edit";
    }
    /**
     * 修改保存讲师
     */
    @Permissions("teacher:edit")
    @Log(title = "编辑讲师", businessType = BusinessType.UPDATE)
    @PostMapping("/save.json")
    @ResponseBody
    public AjaxResult edit(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        String name = TKString.trim(request.getParameter("name"));
        if (TKString.isEmpty(name)) {
            return error("请输入讲师名称");
        }
        int subjectId = TKConvert.toInteger(request.getParameter("subjectId"));
        if (subjectId > 0) {
            Subject subject = subjectService.get(subjectId);
            if (subject == null) return error("找不到指定专业");
        }
        String intro = TKString.trim(request.getParameter("intro"));
        if (TKString.isEmpty(intro)) {
            return error("请输入讲师介绍");
        }
        String tags = TKString.trim(request.getParameter("tags"));
        if (tags.length() > 0) {
            tags = tags.replace("，", ",").replace("/", ",").replace("／", ",");
        }
        int isElite = TKConvert.toInteger(request.getParameter("isElite"));
        int isTop = TKConvert.toInteger(request.getParameter("isTop"));
        int isDisabled = TKConvert.toInteger(request.getParameter("isDisabled"));
        if (isElite != 1) {
            isElite = 0;
        }
        if (isTop != 1) {
            isTop = 0;
        }
        if (isDisabled != 1) {
            isDisabled = 0;
        }
        Teacher teacher;
        if (id > 0) {
            teacher = teacherService.get(id);
            if (teacher == null) {
                return error("找不到指定教师");
            }
        } else {
            String mobile = request.getParameter("mobile");
            if (!TKString.isMobile(mobile)) {
                return error("请输入正确的手机号码");
            }
            teacher = teacherService.getByMobile(mobile);
            if (teacher != null) {
                return error("该手机号码已经被使用，请不要重复添加");
            }
            teacher = new Teacher();
            teacher.setMobile(mobile);
        }
        teacher.setName(name);
        teacher.setAvatar(TKString.trim(request.getParameter("avatar")));
        teacher.setSex(TKConvert.toInteger(request.getParameter("sex")));
        teacher.setBirthday(TKConvert.toLocalDate(request.getParameter("birthday"), null));
        teacher.setNativePlace(TKString.trim(request.getParameter("nativePlace")));
        teacher.setSubjectId(subjectId);
        teacher.setStarId(TKConvert.toInteger(request.getParameter("starId"), 1));
        teacher.setEducation(TKString.trim(request.getParameter("education")));
        teacher.setIntro(intro);
        teacher.setTags(tags);
        teacher.setWorkUnit(TKString.trim(request.getParameter("workUnit")));
        teacher.setWorkDept(TKString.trim(request.getParameter("workDept")));
        teacher.setIsElite(isElite);
        teacher.setIsTop(isTop);
        teacher.setIsDisabled(isDisabled);
        teacher.setViewCount(TKConvert.toInteger(request.getParameter("viewCount")));
        teacher.setLikeCount(TKConvert.toInteger(request.getParameter("likeCount")));
        teacher.setSort(TKConvert.toInteger(request.getParameter("sort")));
        if (!TKString.isEmpty(teacher.getAvatar())) {
            //原图
            String oldPath = teacher.getAvatar();
            //新图
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadAvatarFolder, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, 400, 480);
                teacher.setAvatar(newPath);
            }
        }
        if (teacher.getManagerId() == 0) {
            Manager manager = managerService.getByMobile(teacher.getMobile());
            if (manager != null) {
                teacher.setManagerId(manager.getManagerId());
            } else if (TKConvert.toInteger(request.getParameter("createManager")) == 1) {
                teacher.setManagerId(managerService.insertByTeacher(teacher));
            }
        }
        if (teacher.getUserId() == 0) {
            User user = userService.getByMobile(teacher.getMobile());
            if (user != null) {
                teacher.setUserId(user.getUserId());
            } else {
                teacher.setUserId(userService.insertByTeacher(teacher));
            }
        }
        if (teacher.getId() > 0) {
            return toAjax(teacherService.update(teacher));
        } else {
            return toAjax(teacherService.insert(teacher));
        }
    }

    /**
     * 冻结或启用
     */
    @PostMapping("/disabled.json")
    @ResponseBody
    public AjaxResult disabled(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error("参数异常");
        int isDisabled = TKConvert.toInteger(request.getParameter("isDisabled"));
        Teacher teacher = teacherService.get(id);
        if (teacher == null){
            return error("找不到指定记录！");
        }
        teacher.setIsDisabled(isDisabled >= 1 ? 1 : 0);
        return toAjax(teacherService.updateDisabled(teacher));
    }

    /**
     * 修改排序
     */
    @PostMapping("/sort/edit.json")
    @ResponseBody
    public AjaxResult editSort(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error("参数异常");
        Teacher teacher = teacherService.get(id);
        if (teacher == null){
            return error("找不到指定记录！");
        }
        int sort = TKConvert.toInteger(request.getParameter("sort"));
        int row = teacherService.updateSort(id,sort);
        return toAjax(row);
    }

    /**
     * 删除讲师
     */
    @Permissions("teacher:remove")
    @Log(title = "删除讲师", businessType = BusinessType.DELETE)
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("ids"));
        if (id < 1) error("参数异常");
        return toAjax(teacherService.delete(id));
    }
}
